//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  ShopDetailBoard.m
//  Pizza
//
//  Created by sendInfo on 2015-03-26.
//  Copyright (c) 2015年 sendInfo. All rights reserved.
//

#import "ShopDetailBoard.h"
#import "GoodsCell.h"
#import "Masonry.h"
#import "PullLoader.h"
#import "FootLoader.h"



#pragma mark -

@interface HeadBtnCell : BeeUICell

@end
@implementation HeadBtnCell
SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)
- (void)load
{
    
}

- (void)dataDidChanged
{
    $(@"mask").DATA(self.data);
}

@end




@implementation HeadTypeCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{

    NSArray *titles = @[@"披萨"];
    self.list.whenReloading = ^{
    
        self.list.total = titles.count;
        for (BeeUIScrollItem *item in self.list.items) {
            
            item.size = CGSizeMake(110, 21);
            item.data = [titles safeObjectAtIndex:item.index];
            item.clazz = [HeadBtnCell class];
            
        }
    
    };

}

- (void)dataDidChanged
{
    
}


@end


@implementation GoodsAlertCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)dataDidChanged
{
    
    Goods *gd = self.data;
    $(@"name").DATA(gd.title);
    $(@"pricevalue").DATA([NSString stringWithFormat:@"￥%@",gd.price]);
    $(@"ingredient").DATA([NSString stringWithFormat:@"配料:%@",gd.burdening]);
    $(@"bigphoto").DATA([NSString stringWithFormat:@"%@/%@",[HttpRequest sharedInstance].imageUrl,gd.pic]);
    $(@"content").DATA([NSString stringWithFormat:@"简介:%@",gd.content]);

}


@end


@implementation ShopOneItemCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)dataDidChanged
{
    
   
    GoodsCell *cell1 = (GoodsCell*)$(@"#left").view;
    cell1.data = [self.data firstObject];

    
}


@end

/*==========================================================================================*/

@implementation ShopItemCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)dataDidChanged
{

  
    GoodsCell *cell1 = (GoodsCell*)$(@"#left").view;
    GoodsCell *cell2 = (GoodsCell*)$(@"#right").view;
    cell1.data = [self.data firstObject];
    cell2.data = [self.data lastObject];

}

@end


/*==========================================================================================*/

@interface ShopDetailBoard()
{
	//
    NSArray *goodsData;
    int _row;
    int _col;
    NSMutableArray *UIData;
    UIView *bottomV;
    
    GoodsAlertCell *_currentCell;
    int _num;
    
    UILabel *numLab;
    
    int _selectIndex;
    
    NSMutableDictionary *_selectGoodsD;
    UILabel *priceLab;
}
@end

@implementation ShopDetailBoard

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

DEF_MODEL(GoodM, gm)

- (void)constructUIData:(NSArray *)arr{

    goodsData = arr;

    

    
//    if (arr.count == 1) {
//        
//        [UIData addObject:@[goodsData[0]]];
//        return;
//    }
    
    _row = goodsData.count/2;
    
    if (goodsData.count%2) {
        
        _row++;
        
    }
    if (goodsData.count == 1) {
        
        _row=1;
    }
    
    //组装成二维数组
    for (int i =0; i<_row; i++) {
        
        NSMutableArray *smlArr = [[NSMutableArray alloc] initWithCapacity:0];
        
        _col = (i > goodsData.count/2-1)?1:2;
        
        if (goodsData.count == 1) {
            
            _col =1;
        }
        
        for (int j = 0; j<_col; j++) {
            
            [smlArr addObject:goodsData[2*i+j]];
        }
        
        [UIData addObject:smlArr];
    }
    
    NSLog(@"======%@",UIData);
    
    

}

- (void)load
{
    
     UIData = [[NSMutableArray alloc] initWithCapacity:0];
    self.gm = [GoodM  modelWithObserver:self];
    NSDictionary *select = [[NSUserDefaults standardUserDefaults] objectForKey:@"cart.selectgoods"];
    
    if (select) {
        
        _selectGoodsD = [[NSMutableDictionary alloc] initWithDictionary:select];
        
    }else{
    
        _selectGoodsD = [[NSMutableDictionary alloc] initWithCapacity:0];

    }

    
}

- (void)unload
{
    self.gm = nil;
}

#pragma mark - Signal


ON_CREATE_VIEWS( signal )
{
    
    
    self.gm.shopId = self.sp.id;
    self.gm.categoryId = @"";
    self.gm.keywords = @"";
    
    //
    $(@"shoptitle").DATA(self.sp.title);
    
    [self createBottomView];
    self.list.lineCount = 1;
    self.list.animationDuration = 0.25f;
    
    //self.list.headerClass = [PullLoader class];
    //self.list.headerShown = YES;
    //self.list.footerClass = [FootLoader class];
    //self.list.footerShown = YES;
    
    self.list.whenReloading = ^{
        
        self.list.total = 1+UIData.count;
        
        for (BeeUIScrollItem *item in self.list.items) {
            
            if (item.index == 0) {
                
                item.size = CGSizeMake(self.list.size.width, 35);
                item.clazz = [HeadTypeCell class];
                

            }else{
                
                item.size = CGSizeMake(self.list.size.width, 140);
                NSArray *arr = [UIData safeObjectAtIndex:item.index-1];
                item.data = arr;
                if (arr.count==1) {
                    
                    item.clazz = [ShopOneItemCell class];
                    
                }else{
                    
                    item.clazz = [ShopItemCell class];
                }
                
            }
        }
    
    };
    
    self.list.whenHeaderRefresh = ^{
        
        
        [self.gm firstPage];

    };
    
    self.list.whenFooterRefresh = ^{
        
        
        //[self.gm nextPage];
    };
    

    
    self.list.headerLoading = YES;
    [self.gm firstPage];
    
}

ON_DELETE_VIEWS( signal )
{
    
}

ON_LOAD_DATAS(signal)
{


    

}
ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3(ShopDetailBoard, back, signal)
{

    [self.stack popBoardAnimated:YES transitionType:BeeUITransitionTypeCube];

}
ON_SIGNAL3(GoodsCell, mask, signal)
{

    if (_num==0) {
        
        _currentCell = nil;
    }
    


    [UIView animateWithDuration:0.3 animations:^{
        
        bottomV.frame = CGRectMake(0, self.bounds.size.height-44, self.bounds.size.width, 44);
        
    } completion:^(BOOL finished) {
        
    }];
    
    //alert
    GoodsAlertCell *selectCell = [[GoodsAlertCell alloc] initWithFrame:CGRectMake(15, 115, self.size.width-30, 335)];
    GoodsCell *cell = (GoodsCell*)signal.sourceCell;
    Goods *gd = cell.data;
    selectCell.data = gd;
    selectCell.RELAYOUT();
    [self presentModalView:selectCell animated:YES transition:[BeeUITransition transitionWithType:BeeUITransitionTypeDefault]];
    

}

- (void)createBottomView
{
    
    bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height+44, self.bounds.size.width, 44)];
    bottomV.clipsToBounds = NO;
    [self.view addSubview:bottomV];
    
    UIImageView *leftbg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width/2, 44)];
    leftbg.image = [UIImage imageNamed:@"cartbg"];
    [bottomV addSubview:leftbg];
    [bottomV sendSubviewToBack:leftbg];
    
    UIImageView *cartIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cartIcon"]];
    cartIcon.frame = CGRectMake(10, -20, 60, 60);
    cartIcon.clipsToBounds = NO;
    [bottomV addSubview:cartIcon];
    
    numLab = [[UILabel alloc] initWithFrame:CGRectMake(45, 2, 20, 20)];
    numLab.tag = 7887;
    numLab.backgroundColor = RGB(245, 34, 71);
    numLab.text = @"0";
    numLab.textAlignment = NSTextAlignmentCenter;
    numLab.textColor = [UIColor whiteColor];
    numLab.font = [UIFont systemFontOfSize:14];
    numLab.layer.cornerRadius = 10;
    numLab.layer.masksToBounds = YES;
    [cartIcon addSubview:numLab];
    
    priceLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(cartIcon.frame)+5, 10, 100, 20)];
    priceLab.text = @"共 0.00元";
    priceLab.font = [UIFont systemFontOfSize:16];
    [bottomV addSubview:priceLab];
    
    
    UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftbg.frame), 0, self.bounds.size.width/2, 44)];
    [payBtn setTitle:@"选好了" forState:UIControlStateNormal];
    [payBtn addTarget:self action:@selector(OKSelect) forControlEvents:UIControlEventTouchUpInside];
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    payBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    payBtn.backgroundColor = RGB(245, 34, 71);
    [bottomV addSubview:payBtn];
    
}
- (void)OKSelect
{

    
    

    /**
     *  
     */
    
    
    
    
    _currentCell = nil;
    numLab.text = @"0";
    _num = 0;
    [UIView animateWithDuration:0.3 animations:^{
        
        bottomV.frame = CGRectMake(0, self.bounds.size.height+44, self.bounds.size.width, 44);
        
    } completion:^(BOOL finished) {
        
        //保存选择的产品
        
//        for (NSString *key in [_selectGoodsD allKeys]) {
//            
//            CartM *cm = _selectGoodsD[key];
//            NSDictionary *cmd = [cm objectToDictionary];
//           
//            [_selectGoodsD setObject:cmd forKey:key];
//        }
        

        
        
        
        
        [[NSUserDefaults standardUserDefaults] setObject:_selectGoodsD forKey:@"cart.selectgoods"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSString *sid;
        if (self.sp.shopId.length>0) {
            sid = self.sp.shopId;
        }else{
        
            sid = self.sp.id;
        }
        [[SendIFAPPDefault shareAppDefault] setSelectedGoodsShopID:sid];
        
        [self.stack popToFirstBoardAnimated:YES transition:BeeUITransitionTypeDefault];
    }];
    


}
#pragma mark - 确认选择的产品
ON_SIGNAL3(BeeUIBoard, MODALVIEW_WILL_HIDE, signal)
{


    
    if (_num !=0) {
        
        Goods *gm = _currentCell.data;
        CartM *cm = [CartM new];
        cm.orderType = @"0";
        cm.goodsNum = [NSString stringWithFormat:@"%d",_num];
        cm.goods = gm;
        cm.gid = gm.id;
        
        
        NSDictionary *cd = [cm objectToDictionary];
        [_selectGoodsD setObject:cd forKey:[NSString stringWithFormat:@"%@",gm.title]];

        
        
    }else{
    
        return;
    }
    
    
    
    
    
    int sum=0;
    float price=0.00;
    for (NSDictionary *cmd in [_selectGoodsD allValues]) {
        
        CartM *cm = [CartM objectFromDictionary:cmd];
        
        sum+=[cm.goodsNum intValue];
        price+=[cm.goods.price floatValue]*[cm.goodsNum intValue];
        
        NSLog(@"xxxx%@",cm.goodsNum);
        
    }
    
    
    numLab.text = [NSString stringWithFormat:@"%d",sum];
    priceLab.text = [NSString stringWithFormat:@"共%.2f 元",price];
    
    _num = 0;
    
    
}

ON_SIGNAL3(GoodsAlertCell, minbtn, signal)
{
    _num--;
    if (_num<1) {
        
        _num = 0;
    }
    GoodsAlertCell *cell = (GoodsAlertCell*)signal.sourceCell;
    _currentCell = cell;
    $(cell).FIND(@"#numvalue").DATA(@(_num));
    numLab.text = [NSString stringWithFormat:@"%d",_num];

}
ON_SIGNAL3(GoodsAlertCell, plusbtn, signal)
{

    _num++;
    GoodsAlertCell *cell = (GoodsAlertCell*)signal.sourceCell;
    _currentCell = cell;
    $(cell).FIND(@"#numvalue").DATA(@(_num));
    numLab.text = [NSString stringWithFormat:@"%d",_num];

}


ON_SIGNAL2(GoodM, signal)
{
    
    if ([signal is:GoodM.RELOADING]) {
        
        self.list.footerLoading = YES;
        self.list.headerLoading = YES;
        
        
    }else if ([signal is:GoodM.RELOADED])
    {
        [self dismissTips];
        
        [self.list setHeaderLoading:NO];
        [self.list setFooterLoading:NO];
        [self constructUIData:self.gm.goodsArr];
        [self.list asyncReloadData];
        
    }
}

ON_SIGNAL3(HeadBtnCell, mask, signal)
{

    HeadBtnCell *cell = (HeadBtnCell*)signal.sourceCell;
    NSString *keyw = cell.data;
    self.gm.keywords = keyw;
    if ([keyw isEqualToString:@"全部"]) {
        
        self.gm.keywords = @"";
    }
    self.list.headerLoading = YES;
    [UIData removeAllObjects];
    [self.gm firstPage];
    

}

@end
